package org.cl.tdd;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class ParkingBoy {
    private static final int MAX_PARKING_PLACE_SIZE = 3;
    private PriorityQueue<ParkingPlace> parkingQueue = null;
    private Map<String, ParkingPlace> parkingPlaceMap = new HashMap<String, ParkingPlace>();

    ParkingBoy(Comparator comparator) {
        parkingQueue = new PriorityQueue<ParkingPlace>(MAX_PARKING_PLACE_SIZE, comparator);
    }

    public String parking(Car car) {
        if(parkingQueue.size() == 0){
            return null;
        }
        String parkingSeqNo = parkingQueue.peek().getPlaceNo();
        ParkingPlace parkingPlace = parkingPlaceMap.get(parkingSeqNo);
        parkingPlace.park(car);
        if (parkingPlace.isFull()) {
            parkingQueue.poll();
        }
        return parkingSeqNo;
    }

    public void addParkingPlace(ParkingPlace parkingPlace) {
        parkingPlaceMap.put(parkingPlace.getPlaceNo(), parkingPlace);
        parkingQueue.add(parkingPlace);
    }


    public Car getCar(String carNum) {
        for (String key : parkingPlaceMap.keySet()) {
            ParkingPlace parkingPlace = parkingPlaceMap.get(key);
            boolean isFull = parkingPlace.isFull();
            Car car = parkingPlace.get(carNum);
            if (car != null) {
                if (isFull) {
                    parkingQueue.add(parkingPlace);
                }
                return car;
            }
        }
        return null;
    }
}
